<template>
  <view>
    <ikz-loading :css-data="loading_css"></ikz-loading>
    <view class="example">
      <!-- 基础用法，不包含校验规则 -->
      <uni-forms ref="baseForm" :modelValue="baseFormData" label-position="top">
        <uni-forms-item label="商品名称" required>
          <uni-easyinput
            v-model="baseFormData.name"
            placeholder="请输入商品名称"
          />
        </uni-forms-item>
        <uni-forms-item label="商品图片" required>
          <view class="head-pic">
            <button open-type="chooseAvatar" @chooseavatar="bindchooseavata">
              <image
                :src="baseFormData.image || '/static/add.png'"
                alt=""
                mode="aspectFill"
              ></image>
              <view style="flex: 1"></view>
            </button>
          </view>
        </uni-forms-item>
        <uni-forms-item label="商品规格" required>
          <view class="button-sp-area">
            <button
              class="mini-btn"
              :type="specificationsIndex == item.value ? 'warn' : 'default'"
              size="mini"
              v-for="(item, index) in specifications"
              :key="index"
              @click="specificationsIndex = item.value"
            >
              {{ item.label }}
            </button>
          </view>
        </uni-forms-item>
        <uni-forms-item label="商品价格（元）" required>
          <uni-number-box
            :value="1.0"
            v-model="baseFormData.price"
            :step="0.1"
          />
        </uni-forms-item>
        <uni-forms-item label="商品分类" required>
          <uni-data-select
            v-model="baseFormData.category_id"
            :localdata="classificationList"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="商品介绍" required>
          <uni-easyinput
            type="textarea"
            v-model="baseFormData.introduction"
            placeholder="请输入商品介绍"
          />
        </uni-forms-item>
      </uni-forms>
      <view class="submit">
        <button type="primary" class="confirm-world" @click="getTemplateId">
          确认
        </button>
      </view>
    </view>
  </view>
</template>
<script>
var app = getApp();
import ikz from "@/pages/Common/tools.js";
import ikzLoading from "@/pages/Component/Public/Loading/loading.vue";
export default {
  components: {
    ikzLoading,
  },
  data() {
    return {
      specificationsIndex: 0,
      // 表单
      baseFormData: {
        name: "", //商品名称
        image: "", //图片地址
        price: "", //商品价格
        introduction: "", //商品介绍
        unit: "", //规格
        category_id: "", //商品分类ID
      },
      // 规格
      specifications: [
        {
          value: 0,
          label: "本",
        },
        {
          value: 1,
          label: "件",
        },
        {
          value: 2,
          label: "杯",
        },
        {
          value: 3,
          label: "斤",
        },
        {
          value: 4,
          label: "份",
        },
        {
          value: 5,
          label: "瓶",
        },
      ],
      // 分类，添加模拟数据
      classificationList: [],
      action: "", // 操作类型：add 或 edit
      goodsId: "", // 商品 ID
      template_id: {},
      loading_css: {
        display: "flex",
      },
    };
  },
  onLoad(options) {
    // this.getaaa();
    this.action = options.action;
    this.getClassification();
    this.templateId((res) => {
      this.loading_css.display = "none";
    });
    this.goodsId = options.id;
    if (this.action === "edit") {
      // 如果是编辑操作，根据商品 ID 获取商品详情并填充表单
      this.getGoodsDetail();
      // 修改页面标题为编辑商品
      uni.setNavigationBarTitle({
        title: "编辑商品",
      });
    } else {
      // 如果是添加操作，修改页面标题为添加商品
      uni.setNavigationBarTitle({
        title: "添加商品",
      });
    }
  },
  methods: {
    //获取模板参数
    templateId(fn) {
      var path = "/xyb/wechat_mini_push/template_id_list";
      var data = {};
      ikz.post(path, data, (res) => {
        if (res.data.code) {
          this.template_id = res.data.data;
          console.log("template_id的值", this.template_id);
        } else {
          uni.showModal({
            title: "提示",
            content: res.data.msg,
            showCancel: false,
            success: function (res) {},
          });
        }
        fn();
      });
    },
    // 获取商品详情
    getGoodsDetail: function () {
      // 显示加载提示
      uni.showLoading({
        mask: true,
      });
      var path = `/xyb/supermarket/goods/detail?id=${this.goodsId}`;
      var data = {};
      ikz.get(path, data, (res) => {
        if (res.data.code === 1) {
          const goods = res.data.data;
          this.baseFormData = {
            name: goods.name,
            image: app.globalData.adminImgPath + "/" + goods.image,
            price: goods.price,
            introduction: goods.introduction,
            unit: goods.unit,
            category_id: goods.category_id,
          };
        }
        // 隐藏加载提示
        uni.hideLoading();
      });
    },
    // 提交数据
    getSubmit: function () {
      this.processCancelOrder();
    },
    processCancelOrder() {
      this.baseFormData.unit =
        this.specifications[this.specificationsIndex].label;
      if (this.baseFormData.name == "") {
        uni.showToast({
          title: "请输入商品名称",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.image == "") {
        uni.showToast({
          title: "请上传商品图片",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      if (this.baseFormData.price == "") {
        uni.showToast({
          title: "请输入商品价格",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.introduction == "") {
        uni.showToast({
          title: "请输入商品介绍",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      if (this.baseFormData.category_id == "") {
        uni.showToast({
          title: "请选择商品分类",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      // 显示加载提示
      uni.showLoading({
        mask: true,
      });
      let path;
      let data = { ...this.baseFormData };
      data.image = data.image.replace(/^(?:https?:\/\/)?[^\/]+/, "");
      if (this.action === "edit") {
        // 如果是编辑操作，请求编辑接口
        path = app.globalData.adminPath + "/xyb/supermarket/goods/edit";
        data.id = this.goodsId; // 添加商品 ID
      } else {
        // 如果是添加操作，请求添加接口
        path = app.globalData.adminPath + "/xyb/supermarket/goods/add";
      }
      const _this = this;
      uni.request({
        url: path,
        method: "POST",
        data: data,
        header: {
          token: uni.getStorageSync("local_user_session"),
        },
        success: function (res) {
          if (res.data.code == 0) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          } else {
            uni.showToast({
              title: "添加成功，即将返回",
              icon: "none",
              duration: 3000,
            });

            for (const key in _this.baseFormData) {
              _this.baseFormData[key] = "";
            }
            _this.baseFormData.category_id = "1";
            _this.baseFormData.image = "/static/add.png";
            setTimeout(function () {
              uni.hideLoading();
              uni.redirectTo({
                url: "/pages/Component/merchant/goods/index/index", // 上一页的路径
              });
            }, 2000);
          }
        },
        fail: function (err) {
          console.error("请求失败:", err);
        },
        complete: function () {
          // 隐藏加载提示
        },
      });
    },
    // 获取商品分类
    getClassification: function () {
      // 显示加载提示
      uni.showLoading({
        mask: true,
      });
      var path = "/xyb/supermarket/goods/category";
      var data = {};
      ikz.get(path, data, (res) => {
        if (res.data.code) {
          // 假设响应数据中分类信息在 res.data.data 数组中，每个元素包含 id 和 name
          this.classificationList = res.data.data.map((item) => ({
            value: item.id,
            text: item.name,
          }));
        }
        // 隐藏加载提示
        uni.hideLoading();
      });
    },
    // 上传商品图片
    bindchooseavata: function (val) {
      console.log(val.detail.avatarUrl, "val.detail.avatarUrl");
      uni.showLoading({
        title: "上传中",
        mask: true,
      });
      uni.uploadFile({
        url: app.globalData.adminPath + "/common/upload",
        filePath: val.detail.avatarUrl,
        name: "file",
        formData: {
          token: uni.getStorageSync("local_user_session"),
        },
        success: (uploadFileRes) => {
          if (uploadFileRes.code == 401) {
            console.log(uni.getStorageSync("local_user_session"));
          } else {
            this.baseFormData.image =
              app.globalData.adminImgPath +
              JSON.parse(uploadFileRes.data).data.url;
          }
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },

    //获取模板参数
    getTemplateId: function (fn) {
      var temp_id = [
        this.template_id.user_apply_cancel,
        this.template_id.business_order,
        // this.template_id.business_refuse_user,
      ];

      const _this = this;
      uni.requestSubscribeMessage({
        tmplIds: temp_id,
        success(res) {
          _this.getSubmit();
        },
        fail(res) {
          // that.up_status == 2;
          if (res.errCode == 20004) {
            uni.showModal({
              title: "提示",
              content: "请前往设置打开接受通知",
              confirmText: "确定",
              success(res) {
                _this.getSubmit();
              },
            });
          } else {
            uni.showModal({
              title: "提示",
              content: "未订阅消息，无法接收到订单通知",
              confirmText: "确定",
              success(res) {
                _this.getSubmit();
              },
            });
          }
        },
      });
    },

    // getaaa() {
    //   var path = "/xyb/wechat_mini_push/template_id_list";
    //   var data = {};
    //   ikz.post(path, data, (res) => {
    //     const templateId = res.data.data.business_order;
    //     // 检查是否开启了接受通知
    //     wx.getSetting({
    //       withSubscriptions: true,
    //       success: (settingRes) => {
    //         if (!settingRes.subscriptionsSetting.mainSwitch) {
    //           // 未开启通知，引导用户打开
    //           wx.showModal({
    //             title: "提示",
    //             content: "请先开启接收通知功能, 以便及时收到订单通知",
    //             success: (modalRes) => {
    //               if (modalRes.confirm) {
    //                 wx.openSetting({
    //                   withSubscriptions: true,
    //                   success: () => {
    //                     // 用户打开通知后，继续授权
    //                     this.requestSubscribeMessage(templateId);
    //                   },
    //                 });
    //               }
    //             },
    //           });
    //         } else {
    //           // 已开启通知，直接授权
    //           this.requestSubscribeMessage(templateId);
    //         }
    //       },
    //     });
    //   });
    // },
    // requestSubscribeMessage(templateId) {
    //   const _this = this;
    //   wx.requestSubscribeMessage({
    //     tmplIds: [templateId],
    //     success: (res) => {
    //       if (res[templateId] === "accept") {
    //         // 用户同意授权，继续后续操作
    //         _this.getSubmit();
    //       } else {
    //         // 用户拒绝授权，提示

    //         wx.showModal({
    //           title: "提示",
    //           content: "请授权订阅消息以继续操作，以便及时收到订单通知",
    //           confirmText: "我知道了",
    //           cancelText: "不了不了",
    //           success: (modalRes) => {
    //             if (modalRes.confirm) {
    //               wx.openSetting({
    //                 withSubscriptions: true,
    //                 success: () => {
    //                   // 用户打开通知后，继续授权
    //                   this.requestSubscribeMessage(templateId);
    //                 },
    //               });
    //             }
    //           },
    //         });
    //       }
    //     },
    //     fail: (err) => {
    //       console.error("授权失败:", err);
    //     },
    //   });
    // },
  },
};
</script>
<style lang="scss">
::v-deep .uni-forms-item__label text {
  white-space: nowrap;
}

::v-deep .button-sp-area {
  display: flex;
  flex-wrap: wrap;

  button {
    margin: 10rpx;
  }
}

.example {
  padding: 30rpx;
  background-color: #fff;

  .segmented-control {
    margin-bottom: 30rpx;
  }

  .submit {
    display: flex;
    justify-content: center;

    .confirm-world {
      color: #fff;
      background: #ffc045;
      border-radius: 44rpx;
      width: 100%;
    }

    .confirm-world::after {
      border: none;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: space-around;
  }

  .form-item {
    display: flex;
    align-items: center;
  }

  .button {
    display: flex;
    align-items: center;
    height: 70rpx;
    margin-left: 20rpx;
  }

  .head-pic {
    button {
      overflow: hidden;
      // display: flex;
      text-align: left;
      padding: 0;
      margin: 0;
      height: 120rpx;
      background-color: #fff;
    }

    button::after {
      border: none;
    }

    image {
      overflow: hidden;
      width: 120rpx;
      height: 120rpx;
    }
  }
}
</style>
